<template>
  <el-row>
    <el-col :span="24">
      <!-- <basic-container> -->
      <avue-crud :option="option" :search.sync="search" :table-loading="loading"
        :data="data" ref="crud" v-model="form" :permission="permissionList"
        @row-del="rowDel" @row-update="rowUpdate" @row-save="rowSave"
        :before-open="beforeOpen" :page.sync="page"
        @search-change="searchChange" @search-reset="searchReset"
        @selection-change="selectionChange" @current-change="currentChange"
        @size-change="sizeChange" @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger" size="small" plain icon="el-icon-delete"
            @click="handleDelete">删 除
          </el-button>
        </template>
        <template slot-scope="{ row }" slot="menu">
          <el-button type="text" size="small" icon="el-icon-refresh"
            @click="handleReset(row)">重置密码
          </el-button>
        </template>
        <template slot-scope="{ row }" slot="tenantName">
          <el-tag>{{ row.tenantName }}</el-tag>
        </template>
        <template slot-scope="{ row }" slot="roleName">
          <el-tag>{{ row.roleName }}</el-tag>
        </template>
        <template slot-scope="{ row }" slot="sex">
          <el-tag v-if="row.sex == '0'">男</el-tag>
          <el-tag v-else-if="row.sex == '1'" type="danger">女</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </avue-crud>
      <!-- </basic-container> -->
    </el-col>
  </el-row>
</template>

<script>
  import {
    getList,
    remove,
    update,
    add,
    resetPassword
  } from "@/api/system/user";

  import {
    getRoleTree
  } from "@/api/system/role";
  import {
    byteLength
  } from "@/utils/index";
  import {
    isPhone,
    validEmail
  } from "@/utils/validate";

  export default {
    data() {
      const validatePass = (rule, value, callback) => {
        if (!/^(?=.*[a-zA-Z])(?=.*\d).+$/.test(value)) {
          callback(new Error("密码需包含数字和字母"));
        } else {
          callback();
        }
      };
      const validatePass2 = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再次输入密码"));
        } else if (value !== this.form.password) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      };
      const validatName = (rule, value, callback) => {
        if (byteLength(value) < 2 || byteLength(value) > 20) {
          callback(new Error("请输入2-20位英文字符或1-10位中文字符"));
        } else {
          callback();
        }
      };
      const validatNum = (rule, value, callback) => {
        if (!isPhone(value)) {
          callback(new Error("请输入正确格式的手机号码"));
        } else {
          callback();
        }
      };
      const validatEmail = (rule, value, callback) => {
        if (!validEmail(value)) {
          callback(new Error("请输入正确格式的电子邮箱"));
        } else {
          callback();
        }
      };
      const validAlphabetsASNum = (rule, value, callback) => {
        if (!/^[a-zA-Z0-9]+$/.test(value)) {
          callback(new Error("只能输入英文或数字"));
        } else {
          callback();
        }
      };
      return {
        form: {},
        search: {},
        initFlag: true,
        selectionList: [],
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0,
        },
        init: {
          roleTree: [],
          deptTree: [],
        },
        props: {
          label: "title",
          value: "key",
        },
        treeDeptId: "",
        option: {
          rowKey: "userId",
          // height: "auto",
          // calcHeight: 80,
          columnBtn: false,
          searchShowBtn: false,
          refreshBtn: false,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          selection: true,
          viewBtn: true,
          menuWidth: 300,
          align: "center",
          //dialogType: 'drawer',
          dialogClickModal: false,
          column: [{
              label: 'ID',
              prop: 'id',
              addDisabled: false,
              editDisabled: false,
              addDisplay: false,
              editDisplay: false
            }, {
              label: "登录账号",
              prop: "account",
              search: true,
              display: false,
            },
            {
              label: "用户姓名",
              prop: "name",
              search: true,
              display: false,
            },
            {
              label: "用户性别",
              prop: "sex",
              slot: true,
              display: false,
            },
            {
              label: "所属角色",
              prop: "roleName",
              slot: true,
              display: false,
            },
            {
              label: "手机号",
              prop: "phone",
              slot: true,
              display: false,
            },
            {
              label: "邮箱",
              prop: "email",
              slot: true,
              display: false,
            },
          ],
          group: [{
              label: "基础信息",
              prop: "baseInfo",
              icon: "el-icon-user-solid",
              column: [{
                  label: "登录账号",
                  prop: "account",
                  rules: [{
                      required: true,
                      message: "请输入登录账号",
                      trigger: "blur",
                    },
                    {
                      required: true,
                      validator: validAlphabetsASNum,
                      trigger: "blur",
                    },
                    {
                      min: 2,
                      max: 16,
                      message: "请输入2-16位字符",
                      trigger: "blur",
                    },
                  ],
                },
                {
                  label: "密码",
                  prop: "password",
                  hide: true,
                  editDisplay: false,
                  viewDisplay: false,
                  rules: [{
                      required: true,
                      message: "请输入密码",
                      trigger: "blur",
                    },
                    {
                      required: true,
                      validator: validatePass,
                      trigger: "blur"
                    },
                    {
                      min: 6,
                      max: 16,
                      message: "请输入6-16位字符",
                      trigger: "blur",
                    },
                  ],
                },
                {
                  label: "确认密码",
                  prop: "password2",
                  hide: true,
                  editDisplay: false,
                  viewDisplay: false,
                  rules: [{
                      required: true,
                      message: "请输入密码",
                      trigger: "blur"
                    },
                    {
                      required: true,
                      validator: validatePass2,
                      trigger: "blur"
                    },
                  ],
                },
              ],
            },
            {
              label: "详细信息",
              prop: "detailInfo",
              icon: "el-icon-s-order",
              column: [{
                  label: "用户姓名",
                  prop: "name",
                  rules: [{
                      required: true,
                      message: "请输入用户昵称",
                      trigger: "blur",
                    },
                    {
                      required: true,
                      validator: validatName,
                      trigger: "blur"
                    },
                  ],
                },
                {
                  label: "手机号码",
                  prop: "phone",
                  overHidden: true,
                  rules: [{
                      required: true,
                      message: "请输入手机号码",
                      trigger: "blur",
                    },
                    {
                      required: true,
                      validator: validatNum,
                      trigger: "blur"
                    },
                  ],
                },
                {
                  label: "电子邮箱",
                  prop: "email",
                  // hide: true,
                  overHidden: true,
                  rules: [{
                      required: true,
                      message: "请输入电子邮箱",
                      trigger: "blur",
                    },
                    {
                      required: true,
                      validator: validatEmail,
                      trigger: "blur"
                    },
                  ],
                },
                {
                  label: "用户性别",
                  prop: "sex",
                  type: "select",
                  value: "2",
                  clearable: false,
                  dicData: [{
                      label: "男",
                      value: "0",
                    },
                    {
                      label: "女",
                      value: "1",
                    },
                    {
                      label: "未知",
                      value: "2",
                    },
                  ],
                },
              ],
            },
            {
              label: "职责信息",
              prop: "dutyInfo",
              icon: "el-icon-s-custom",
              column: [{
                label: "所属角色",
                prop: "roleId",
                multiple: false,
                type: "tree",
                dicData: [],
                props: {
                  label: "roleName",
                  value: "roleId",
                },
                checkStrictly: true,
                slot: true,
                rules: [{
                  required: true,
                  message: "请选择所属角色",
                  trigger: "click",
                }, ],
              }, ],
            },
          ],
        },
        data: [],
      };
    },
    watch: {},
    computed: {
      permissionList() {
        return {
          addBtn: true,
          viewBtn: true,
          delBtn: true,
          editBtn: true,
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach((ele) => {
          ids.push(ele.userId + "");
        });
        return ids;
      },
    },
    mounted() {
      this.initData();
    },
    methods: {
      initData() {
        getRoleTree().then((res) => {
          const column = this.findObject(this.option.group, "roleId");
          column.dicData = res.data;
        });
      },
      rowSave(row, done, loading) {
        row.roleIds = [row.roleId + ""];
        row.password = row.password;
        row.userType = "00";
        add(row).then(
          () => {
            this.initFlag = false;
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            done();
          },
          (error) => {
            //console.log(error);
            loading();
          }
        );
      },
      rowUpdate(row, index, done, loading) {
        row.roleIds = [row.roleId + ""];
        update(row).then(
          () => {
            this.initFlag = false;
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            done();
          },
          (error) => {
            //console.log(error);
            loading();
          }
        );
      },
      rowDel(row) {

        this.$confirm("确定删除该用户?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            return remove([row.id]);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
          });
      },
      searchReset() {
        this.query = {};
        this.treeDeptId = "";
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleReset(row) {
        console.log(row);
        this.$confirm("确定将该用户密码重置为123456?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            return resetPassword(row.id);
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        this.initFlag = true;
        done();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList({
            current: page.currentPage,
            size: page.pageSize
          },
          Object.assign(params, this.query),
          this.treeDeptId
        ).then((res) => {
          const data = res.data;

          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
    },
  };
</script>

<style>
  .box {
    height: 800px;
  }

  .el-scrollbar {
    height: 100%;
  }

  .box .el-scrollbar__wrap {
    overflow: scroll;
  }
</style>
